#include <iostream>
#include <string>
#include <sstream>
#include <memory>
#include <jsoncpp/json/json.h>

// 实现数据的序列化
// 实现json字符串的反序列化

bool serialize(const Json::Value &val, std::string& body)
{

    std::stringstream ss;
    // 先实例化一个工厂类对象
    Json::StreamWriterBuilder swb;
    // 通过工厂类对象来实例化派生类对象
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    int ret = sw->write(val, &ss);
    if(ret != 0)
    {
        std::cout<<"json serialize failed!\n";
        return false;
    }
    body = ss.str();
    return true;
}

int main()
{
    const char *name = "小明";
    int age = 18;
    const char *sex = "男";
    float score[3] = {88, 77.5, 66};

    Json::Value student;
    student["姓名"] = name;
    student["年龄"] = age;
    student["性别"] = sex;
    student["成绩"].append(score[0]);
    student["成绩"].append(score[1]);
    student["成绩"].append(score[2]);

    Json::Value fav;
    fav["书籍"] = "西游记";
    fav["运动"] = "打篮球";
    student["爱好"] = fav;

    std::string body;
    serialize(student,body);
    
    std::cout<< body<<std::endl;
    return 0;
}